package com.label.grade.utils;

import org.jetbrains.annotations.NotNull;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class ExamSemesterCalculatorUtil {
    /**
    * @Description: 根据入学年份和时间判断学年学期
    * @Param: 入学年份：2020，时间20220901
    * @return: map
    * @Author: i++
    * @Date: 2023/7/10
    */
    public static Map<String,Integer> main(String enrollYear, String examTime) {

        LocalDate enrollmentDate = LocalDate.of(Integer.parseInt(enrollYear), 9, 1);
        LocalDate examDate = LocalDate.of(Integer.parseInt(examTime.substring(0, 4)), Integer.parseInt(examTime.substring(4, 6)), Integer.parseInt(examTime.substring(6, 8)));

        int academicYear = calculateAcademicYear(enrollmentDate, examDate);
        int semester = calculateSemester(enrollmentDate, examDate);

//        System.out.println("考试时间是第 " + academicYear + " 学年的第 " + semester + " 学期");
        Map<String,Integer> map = new HashMap<>();
        map.put("academicYear",academicYear);
        map.put("semester",semester);
        return map;
    }

    private static int calculateAcademicYear(LocalDate enrollmentDate, LocalDate examDate) {
        long monthsBetween = ChronoUnit.MONTHS.between(enrollmentDate, examDate);
        int years = (int) Math.ceil(monthsBetween / 12.0); // 向上取整
        return years; // 入学年份为第一学年
    }

    private static int calculateSemester(LocalDate enrollmentDate, LocalDate examDate) {
        long monthsBetween = ChronoUnit.MONTHS.between(enrollmentDate, examDate);
        int semesters = (int) Math.ceil(monthsBetween / 6.0); // 向上取整
        return semesters % 2 == 0 ? 2 : 1; // 偶数学期为第二学期，奇数学期为第一学期
    }


    /**
     * @param studentCode
     * @param year 2021
     * @param semester 春季学期 秋季学期
     * @return 1:秋季学期 2：春季学期
     */
    @NotNull
    public static Map<String,Integer> getYearSemester(String studentCode, Long year, String semester) {
        Integer academicYear = year.intValue() - Integer.parseInt("20" + studentCode.substring(0,2));
        if(semester.equals("秋季学期")) academicYear++;
        Map<String,Integer> map = new HashMap<>();
        map.put("academicYear",academicYear);
        if(Objects.equals(semester,"秋季学期")){
            map.put("semester",1);
        }else if(Objects.equals(semester,"春季学期")){
            map.put("semester",2);
        }
        return map;
    }
}
